package com.taglab.chic.mvc.spring;

import org.springframework.web.servlet.handler.AbstractHandlerMapping;
import org.springframework.web.HttpRequestHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.util.Properties;
import java.io.IOException;

/**
 * @author Markus Kobler
 */
public class RedirectHandlerMapping extends AbstractHandlerMapping {

  private Properties redirects;

  // XXX add support for reloading


  public void setRedirects(Properties redirects) {
    this.redirects = redirects;
  }

  @Override
  protected Object getHandlerInternal(HttpServletRequest request) throws Exception {
    return lookupRedirect(request);
  }


  protected RedirectHandler lookupRedirect(HttpServletRequest request ) {

    String destination = (String)redirects.get(request.getRequestURI());

    if( destination != null ) {
      return  new RedirectHandler(destination);
    }
    
    return null;
  }


  /**
   *
   * XXX Add support for perm redirects, codes etc
   */
  private class RedirectHandler implements HttpRequestHandler {

    private String destination;

    private RedirectHandler(String destination) {
      this.destination = destination;
    }

    public void handleRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      response.sendRedirect(destination);
    }

  }

}